var util = require('../../../utils/util.js');
var ajax = require('../../../utils/ajax.js');
var common = require('../../../utils/common.js');
var PageBase = require('../../../common/PageBase.js');
var WxParse = require('../../../utils/wxParse/wxParse.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    isLogin: false,
    id: null,
    isHasAttr: 0, //是否有规格0 没有 1有
    actType: 0, //判断是什么活动的商品
    dataLoaded: false,
    winHei: 0,
    swiperHei: 0,
    curSwiperIndex: 0,
    shop: {},
    postage: 0,
    curSkuItem: {
      skuId: null,
      price: null,
      amount: null
    },
    skuList:[],
    skuJson:[],
    num: null,

    //弹出浮层
    panel: {
      type: 1, //1.立即购买2.加入购物车
      isShow: false,
      aimation: {},
      opacityAnimation: {},
      height: 0,
      phone: '',
      yzm: '',
      yzmTime: 0
    },

    //库存计数器
    counter: {
      number: 1,
      minusDisabled: false,
      addDisabled: false,
    },
    canPay: false,
    //isCollected: false,
    cartAmount: 0,
    sharetitle: ''
  },

  onLoad(options) {
    common.initApp({
      loginSuc: () => {
        this._fetch();
        this.setData({
          isLogin: !!app.getUid(),
        });
      }
    });
    this.setData({
      id: this.options.id,
      // isLogin: !!app.getUserSid(),
      // canPay: app.getCanPay(),
      winHei: app.getWinHei()
    });
  },

  _fetch() {
    var $this = this;
    ajax.P({
      url: 'm=goods&c=index&a=info&id=' + this.options.id,
      data: {},
      success: (res) => {
        if (res.code == 1){
          this.setData({
            dataLoaded: true
          })
          util.showWarn(res.msg);
          setTimeout(function(){
            wx.navigateBack({
              delta: 1
            })
          },2500)
        };
        if (res.data.isgroups == 1){

          this.setData({
            dataLoaded: true
          })
          util.showWarn("商品已经下架");
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 2500)
          
        }

        var goodsInfo = res.data;
        
        
          this.setData({
            shareTitle: goodsInfo.intro || goodsInfo.name
          })
        

        if (goodsInfo.shop.length <= 0){
          this.setData({
            isStore: 1,
            storeInfo: app.getStoreInfo()
          });
        }

        //商品详情处理
        if (goodsInfo.content) {
          WxParse.wxParse('article', 'html', goodsInfo.content, this, 0);
        }
        //如果是秒杀商品
        if (goodsInfo.isseckill == "1"){
          console.log("秒杀");
          $this._lastTime = goodsInfo.lasttime;
          // 状态
          var seckillstatus = goodsInfo.seckillstatus;
          // 如果倒计时小于0，自动变成结束状态
          if ($this._lastTime <= 0){
            seckillstatus = 3;
          }
          this.setData({
            actType: 1,
            seckillstatus: seckillstatus, //1为正在进行中，2为未开始，3为已结束
            lastTimeStr: util.getTimeBySec($this._lastTime || 0),
          })
        };

        var feetrans,skulist,skuJson;

        // 如果有规格
        if (goodsInfo.attr.length > 0){
            console.log("有规格");
            skulist = goodsInfo.attr;
            skuJson = goodsInfo.attrprice;
          //默认选中第一个
          if (skulist[0]) {
            skulist[0].data[0].selected = true;
          };
          if (!!skulist[1]) {
            skulist[1].data[0].selected = true;
          };
          // 有规格
          this.setData({
            dataLoaded: true,
            isHasAttr: 1,
            skuList: skulist,
            skuJson: skuJson,
            num: goodsInfo.num,
            goodsInfo
          });
          this._setSkuItem();
        }
        else{
          // 有规格
          this.setData({
            dataLoaded: true,
            num: goodsInfo.num,
            goodsInfo
          });

        };

                
        //this._resetCounter();

        if ($this._actTimer) {
          clearTimeout($this._actTimer);
        }
        if ($this._lastTime > 0) {
          $this._actTimerDown();
        };
        // 获取购物车数量
        this._getCartAmount();

      }
    });
  },

  // 秒杀商品倒计时
  _actTimerDown() {
    var _self = this;
    var sec = _self._lastTime;
    var lastTimeStr = util.getTimeBySec(sec);

    _self.setData({
      lastTimeStr,
    });
    if (sec <= 0) {
      clearTimeout(_self._actTimer);
      _self._initPage();
      return;
    }
    _self._lastTime = _self._lastTime - 1000;
    _self._actTimer = setTimeout(function () {
      _self._actTimerDown();
    }, 1000)
  },
  /**
 * 加入购物车
 */
  _addCart: function (evt) {
    var formId = evt.detail.formId;

    //common.submitForm(formId);

    if (this.data.isLogin) {
      this._showPanel(2);
    } else {
      // wx.navigateTo({
      //   url: '/pages/login/login'
      // });
    }
  },

  /**
   * 确定加入购物车
   */
  _confirmAddCart: function (evt) {
    var self = this;
    var formId = evt.detail.formId;
    if (!self._validSubmit()) {
      return;
    }
    self.setData({
      dataLoaded: false
    });

    // self._login(function () {
    //   ajax.P('/openapi/CCart/add', {
    //     goodsId: self.data.goodsId,
    //     skuId: self.data.curSkuItem.skuId,
    //     amount: self.data.counter.number,
    //   }, function (data) {
    //     self._closePanel();
    //     util.showOK('加入购物车成功');

    //     self._getCartAmount();
    //   });
    // });

    ajax.P({
      url: "m=goods&c=cart&a=add",
      data: {
        uid: app.getUid(),
        gid: self.data.id,
        gaid: self.data.curSkuItem.skuId || '',
        num: self.data.counter.number,
      },
      success: (res) => {
        self._closePanel();
        util.showOK('加入购物车成功');
        self._getCartAmount();
      }
    });
    //common.submitForm(formId);

  },

  /**
   * 获取购物车数量
   */
  _getCartAmount: function () {
    var self = this;

    if (!self.data.isLogin) {
      return;
    }

    ajax.G({
      url: "m=goods&c=cart",
      data: {
        uid: app.getUid()
      },
      success: (res) => {
        var cartList = res.data;
        var cartnum = 0;

        cartList.forEach(function (item) {
          var goods = item.goods;
          cartnum += goods.length;
        });
        console.log(cartnum);
        this.setData({
          cartAmount: cartnum || 0
        })
      }
    });
  },

  //
  _validSubmit() {
    var self = this;
    if (self.data.isHasAttr == 1){

        if (self.data.curSkuItem.amount != null) {
          if (self.data.counter.number > self.data.curSkuItem.amount) {
            util.alert('库存不足');
            return false;
          } else if (self.data.counter.number <= 0) {
            util.alert('请输入正确的购买数量哦~');
            return false;
          }
        }
        else {
          if (self.data.counter.number > self.data.num) {
            util.alert('库存不足');
            return false;
          } else if (self.data.counter.number <= 0) {
            util.alert('请输入正确的购买数量哦~');
            return false;
          }
        }

    }
    else{


    }

    return true;
  },

  /**
   * 立即购买
   */
    _buy: function (evt) {
      var formId = evt.detail.formId;
      //common.submitForm(formId);

      if (this.data.isLogin) {
        this._showPanel(1);
      } else {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }
    },

    /**
     * 倒计时
    */
    _timerDown: function (time) {
      var panel = this.data.panel;

      panel.yzmTime = --time;
      this.setData({
        panel
      });
      if (time == 0) {
        return;
      }
      setTimeout(function () {
        this._timerDown(time);
      }.bind(this), 1000);
    },

    /**
     * 展示购买浮层
     */
    _showPanel(ty) {
      var $this = this;
      var panel = this.data.panel;

      panel.type = ty;
      $this.animation = wx.createAnimation({
        duration: 200,
        timingFunction: "ease-out"
      });
      $this.opacityAnimation = wx.createAnimation({
        duration: 200,
        timingFunction: "ease-out"
      });

      panel.isShow = true;
      $this.setData({
        panel
      });

      setTimeout(function () {
        $this.animation.translateY(0).step();
        $this.opacityAnimation.opacity(1).step();

        panel.animation = $this.animation.export();
        panel.opacityAnimation = $this.opacityAnimation.export();

        $this.setData({
          panel
        });
      }, 0);
    },

    /**
     * 关闭购买浮层
     */
    _closePanel(evt) {
      var $this = this;
      var panel = this.data.panel;
      $this.animation.translateY('100%').step();
      $this.opacityAnimation.opacity(0).step();

      panel.animation = $this.animation.export();
      panel.opacityAnimation = $this.opacityAnimation.export();

      $this.setData({
        panel,
        dataLoaded: true
      })
      setTimeout(function () {
        panel.isShow = false;
        $this.setData({
          panel
        });
      }, 500)
      if (evt) {
        var formId = evt.detail.formId;
        //common.submitForm(formId);
      }

    },

    /**
     * sku变化时，重制计数器
     */
    _resetCounter() {
      var amount = +this.data.curSkuItem.amount; //当前库存
      var counter = this.data.counter;

      if (counter.number > amount) {
        counter.number = amount;
      }

      counter.minusDisabled = counter.number <= 0;
      counter.addDisabled = counter.number >= amount;
      this.setData({
        counter
      });
    },

    /**
     * 计数器+
     */
    _add: function (evt) {
      var counter = this.data.counter;
      var formId = evt.detail.formId;
      var max = evt.currentTarget.dataset.max;

      if (max != undefined && ++counter.number > max) {
        counter.number = max;
      }
      if (counter.number == max && max == 0) {
        counter.addDisabled = true;
      } else if (counter.number == max && max != 0) {
        counter.addDisabled = true;
      } else {
        counter.minusDisabled = false;
      }
      this.setData({
        counter,
      });
      //common.submitForm(formId);
    },

    /**
     * 计数器-
     */
    _minus: function (evt) {
      var counter = this.data.counter;
      var formId = evt.detail.formId;
      var min = evt.currentTarget.dataset.min;

      if (min != undefined && --counter.number < min) {
        counter.number = min;
      }
      if (counter.number < 0) {
        counter.number = 0;
      }
      if (counter.number == min) {
        counter.minusDisabled = true;
      } else {
        counter.addDisabled = false;
      }

      this.setData({
        counter
      });
      //common.submitForm(formId);
    },

    /**
     * 计数量input输入
     */
    _changeNum: function (evt) {
      var val = parseInt(evt.detail.value) || 1;
      var counter = this.data.counter;

      counter.number = val;
      this.setData(counter);
    },

    /**
     * 根据窗口大小，初始化组件宽高
     */
    _initSizeByWin: function () {
      var $this = this;
      // var panel = this.data.panel;

      wx.getSystemInfo({
        success: function (res) {
          // panel.height = res.windowHeight * 0.85;
          $this.setData({
            swiperHei: res.windowWidth * 0.53,
            // panel
          });
        }
      })
    },

    /**
     * 重组sku列表数据结构
     */
    // _setSkuList() {
    //   var goodsSku = this._goodsSku;
    //   var skuList = this.data.skuList;

    //   Object.keys(goodsSku).forEach(function (key) {
    //     var skuArr = goodsSku[key];
    //     var skuItem = {
    //       text: key,
    //       skuArr: [],
    //     }

    //     skuArr.forEach(function (text, index) {
    //       skuItem.skuArr.push({
    //         text: text,
    //         selected: index == 0 ? true : false
    //       })
    //     });
    //     skuList.push(skuItem)
    //   });

    //   this.setData({
    //     skuList: skuList
    //   });
    // },

    /**
     * 设置当前选中sku,并修改显示的价格和库存
     */
    _setSkuItem() {
      var $this = this;
      var skuList = this.data.skuList;
      //var skuJson = this._skuJson;
      var skuJson = this.data.skuJson;

      var curSkuItem;
      var selectedObj = {};

      skuList.forEach(function (group) {
        group.data.some(function (skuItem) {
          if (skuItem.selected) {
            selectedObj[group.name] = skuItem.name;
            return true;
          }
        });
      });

      skuJson.some(function (sku) {
        if (JSON.stringify(sku.name) == JSON.stringify(selectedObj)) {
          curSkuItem = {
            skuId: sku.id,
            price: sku.price,
            amount: $this.data.num
          }
          return true;
        }
      });
      this.setData({
        curSkuItem: curSkuItem,
      });
      console.log(this.data.curSkuItem);
    },

    /**
     * swiper切换时
     */
    _swiperChange: function (evt) {
      this.setData({
        curSwiperIndex: evt.detail.current,
      });
    },

    /**
   * 预览图片
   */
    _previewImg: function (evt) {
      var formId = evt.detail.formId;
      wx.previewImage({
        current: this.data.imageUrls[this.data.curSwiperIndex],
        urls: this.data.imageUrls,
      })
      //common.submitForm(formId);
    },

    /**
     * 选择sku
     */
    _selectSku(evt) {
      var {
          groupIndex,
          skuIndex
        } = evt.currentTarget.dataset;
      var skuList = this.data.skuList;
      var groupObj = skuList[groupIndex];

      groupObj.data.forEach(function (sku, index) {
        sku.selected = index == skuIndex;
      });

      this.setData({
        skuList: skuList,
      });

      this._setSkuItem();
      this._resetCounter();

    },

    /**
     * 确定下单
     */
    _confirmBuy(evt) {
      var uid = app.getUid();
      var self = this;
      var formId = evt.detail.formId;

      if (!self._validSubmit()) {
        return;
      }
      
      quickBuy();

      function quickBuy() {
        self.setData({
          dataLoaded: false
        });
        var {
          actId,
          actType,
          groupBuyId,
            } = self.options;
        var ajaxParams = {
          uid: uid,
          gids: self.data.id,
          aids: self.data.curSkuItem.skuId || '',
          nums: self.data.counter.number,
          isseckill: self.data.actType
        };
        ajax.P({
          url: 'm=order&c=add&a=tmp',
          data: ajaxParams,
          success: (res) => {
            var tmpOrderId = res.data.id;
            self.setData({
              dataLoaded: true
            });
            self._closePanel();
            wx.navigateTo({
              url: '../confirmOrder/index?goodsId=' + self.data.id + '&skuId=' + self.data.curSkuItem.skuId + '&amount=' + self.data.counter.number + '&tmpOrderId=' + tmpOrderId
            })
          }
        });

      }

      // self._closePanel();
      // console.log(this.data.curSkuItem);
      // debugger
      // wx.navigateTo({
      //   url: '/pages/goods/confirmOrder/index?goodsId=' + self.data.goodsId
      // })
      //common.submitForm(formId);
    },


    onShareAppMessage: function (res) {
      return {
        title: this.data.shareTitle,
        path: '/pages/goods/detail/detail?id=' + this.data.id,
        success: function (res) {
          // 转发成功
        },
        fail: function (res) {
          // 转发失败
        }
      }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
      clearTimeout(this._actTimer);
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
      clearTimeout(this._actTimer);
    },

    //分享
    _showActionSheet() {
      this.onShareAppMessage();
      // var {
      //   goodsId,
      //   actId,
      //   actType
      //   } = this.options;
      // var {
      //       isFenxiao
      //   } = this.data;
      // var shareParams = {
      //   type: isFenxiao ? 2 : 1,
      //   goodsId: goodsId,
      // };

      // if (actId) { //活动
      //   if (actType == 0) { //秒杀
      //     shareParams.type = 5;
      //     shareParams.actId = actId;
      //   } else if (actType == 1) { //团购
      //     shareParams.type = 3;
      //     shareParams.actId = actId;
      //   }
      // }
      // this._shareAs.show(shareParams);
    }

}));